<template>
  <t-dialog :visible.sync="visible" header="编 辑"   @confirm="handleConfirm"
    @cancel="handleCancel" @close="handleCancel" >
    <t-form ref="formRef" :data="form" :rules="rules" >
      <t-form-item label="名 称" required name="name">
        <t-input v-model="form.name" placeholder="请输入" clearable  />
      </t-form-item>
      <t-form-item label="规 格">
        <t-input v-model="form.specification" placeholder="请输入" clearable  />
      </t-form-item>
      <t-form-item label="生产厂家">
        <t-input v-model="form.manufacturer" placeholder="请输入" clearable  />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import { ref, defineExpose } from 'vue';
import { MessagePlugin, FormRules, } from 'tdesign-vue-next';
import { update, getById, Model } from '@/api/userCenter/material/material';
const visible = ref?.(false);
const loading = ref?.(false);
const formRef = ref?.(null);
const rules: FormRules = {};
const form = ref?.({
  id: '',
  name: '',
  specification: '',
  manufacturer: ''
});
const handleConfirm = async () => {
  if (!formRef) return;  
  // 先进行表单验证
  const valid = await formRef?.value?.validate?.();
  if (valid !== true) {
    return;
  }
  loading.value = true;
  try {
    const data = form.value as unknown as Model;
    await update(form.value);
    MessagePlugin?.success?.(`操作成功`);
    visible.value = false;
    emit?.('success');
    formRef?.value?.reset();
     
  } catch (t) {
  } finally {
    loading.value = false;
  }
};
const handleCancel = () => {
  visible.value = false;
};
const openDialog = async (id?: string) => {
  visible.value = true;
  if (id) {
    loading.value = true;
    form.value.id = id;
    
    const val = await getById(id);
    if (val && Object.keys(val).length)  {
      form.value = { ...form?.value, ...val, }
    }
    loading.value = false;
  }
};
defineExpose({
  openDialog,
});
const emit = defineEmits(['success']);
</script>
<style lang="less" scoped>
/* 可以在这里添加自定义样式 */
</style>
